class ItemTag < ActiveRecord::Base
  belongs_to :item
  belongs_to :tag
  
  class << self
    def crt_tags(tags,item_id)
      unless tags.strip.eql? ''
        tags.strip.split(" ").each do |t|
          tag = Tag.find :first,:select=>"id,name",:conditions=>["lower(name)=?",t.to_s.downcase] 
          if tag.nil?
            tag = Tag.create do |tg|
                    tg.name=t.to_s
                    tg.status=0
                    tg.flag=0
                    tg.created_at=Time.now
                    tg.updated_at=Time.now
            end
            ItemTag.create do |it|
              it.item_id=item_id
              it.tag_id=tag.id
              it.name=tag.name
              it.total_num=0
              it.status=0
              it.created_at=Time.now
              it.updated_at=Time.now
            end 
          else
            itemtag = ItemTag.find_by_tag_id_and_item_id(tag.id,item_id)
            if itemtag.nil?
              ItemTag.create do |it|
                it.item_id=item_id
                it.tag_id=tag.id
                it.name=tag.name
                it.total_num=1
                it.created_at=Time.now
                it.updated_at=Time.now
              end
            else
                ItemTag.update_counters(itemtag.id,:total_num=>1)
            end
          end#if
        end#each
      end#unless
    end#crt_tags
  end#class

end
